#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    By :陈狍子 e4ting@qq.com 2024-12-07 22:10:24
"""
import sys,os,time,json
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack

from transitions import Machine
from setproctitle import getproctitle,setproctitle
from e4ting import util,log

from .game   import Game
from .player import GamePlayer
from .cash        import Utxo,VirtualAccount

from core.control import Notify
from models.mysqls import ModelCash,ModelRoom,ModelRoomSeat,db
from core.cache    import RoomCache

class Seat():
    states = ['null', 'play', 'disable']

    # 座位
    def __init__(self, number=0):
        self.number = number
        self.player = None
        self.room   = None
        self.key    = "seat_{}".format(number)
        self.machine = Machine(model=self, states=self.states, initial=self.states[0], after_state_change="after_state_change")

    def after_state_change(self):
        log.info(f"{self} => state={self.state}")
        self.room.cache.set(**{f"{self.key}_stat": self.state})
        self.update_record()

    def set_room(self, room):
        self.room = room
        self.state = self.room.cache.get(f"{self.key}_stat") or "null"
        return self

    def set_player(self, player):
        # 玩家入座
        self.player = player
        self.room.cache.set(**{self.key : player.uid})
        self.to_play()
        return self

    def unset_player(self):
        # 玩家离座
        self.player = None
        self.room.cache.set(**{self.key : ""})
        self.to_null()
        return True

    def unable(self):
        # self.player = None
        self.to_disable()
        return True

    def enable(self):
        # self.player = None
        self.to_null()
        return True

    def get_player(self):
        return self.room.cache.get(self.key) or ""

    def has_player(self):
        p = self.get_player()
        return bool(p)

    def get_record(self):
        item = db.session.query(ModelRoomSeat).filter( (ModelRoomSeat.room==self.room.uid) & (ModelRoomSeat.number==self.number) ).first()
        if not item:
            return None
        return item

    def update_record(self):
        db.session.query(ModelRoomSeat).filter((ModelRoomSeat.room==self.room.uid) & (ModelRoomSeat.number==self.number)).update({
            ModelRoomSeat.uid    : self.player.uid if self.player else 0,
            ModelRoomSeat.status : self.state,
        })
        db.session.commit()

    def create_record(self):
        # 避免重复创建
        if item := self.get_record():
            return item.id

        item = ModelRoomSeat(
                room=self.room.uid,
                number=self.number,
                uid=self.player.uid if self.player else 0,
                status=self.states[0],
                )
        db.session.add(item)
        db.session.commit()
        return item.id

    def webdump(self):
        return {
            "number" : self.number,
            "key"    : self.key,
            "uid"    : self.get_player(),
            "status" : self.state,
        }

    def __repr__(self):
        return f"Seat({self.key}, room={self.room})"

if __name__ == '__main__':
    room = Room()
    room.run()
